//
//  CityViewModel.m
//  didacar
//
//  Created by 度周末网络-王腾 on 15/12/18.
//  Copyright © 2015年 dzmmac. All rights reserved.
//

#import "CityViewModel.h"
#import "CityAreaModel.h"
#import "CommoneTools.h"
@implementation CityViewModel

-(id)init{
    self.resultData = [[NSMutableArray alloc ] init];
    return [super init];
}

-(void)loadData:(DealDataResultBlock)resultBlock{
   
    WEAKSELF
    [[BaseHttpRequest sharedInstance] sendRequestToPost:CityArea withData:nil alertMessage:nil success:^(NSDictionary *dicData) {
        
        NSMutableArray *areaList = [dicData objectForKey:@"cityList"];;
      
        NSMutableDictionary *areaDic = [[NSMutableDictionary alloc ] init];
        [areaDic setObj:areaList forKey:@"CityAreaList"];
        [CommoneTools saveDishFile:@"CityArea" dic:areaDic];
        weakSelf.initDataSuccess = YES;
        resultBlock(1,areaList,nil);
    } error:^(NSString *errorMsg) {
        weakSelf.initDataSuccess = NO;
        resultBlock(0,nil,errorMsg);
    }];
}

// 获取城市列表数据。先从缓存中获取。如果没有则请求接口
-(void)getCityAreaList:(DealDataResultBlock)resultBlock{
    
    
    __block NSDictionary *cityDic = [CommoneTools loadDishFile:@"CityArea"];
    // 缓存中没有数据
    if ((cityDic==nil || [cityDic objectForKey:@"CityAreaList"]==nil) && self.initDataSuccess) {
        
        // 请求接口
        [self loadData:^(NSInteger resultType, id data, NSString *errorMsg) {
            if (resultType == 1) {
                for (NSDictionary *dic in data) {
                    CityAreaModel *cityAreaModel = [[CityAreaModel alloc ] initWithDictionary:dic];
                    [self.resultData addObject:cityAreaModel];
                }
                resultBlock(1,nil,nil);
            }else{
                resultBlock(0,nil,errorMsg);
            }
        }];
    }else{
        for (NSDictionary *dic in [cityDic objectForKey:@"CityAreaList"]) {
            CityAreaModel *cityAreaModel = [[CityAreaModel alloc ] initWithDictionary:dic];
            [self.resultData addObject:cityAreaModel];
        }
        resultBlock(1,nil,nil);
    }
}



@end
